<?php

require_once WACT_ROOT . 'controller/controller.inc.php';
require_once WACT_ROOT . 'controller/form.inc.php';
require_once WACT_ROOT . 'validation/rules/match.inc.php';
require_once WACT_ROOT . 'validation/rules/member.inc.php';
require_once WACT_ROOT . 'validation/rules/pattern.inc.php';
require_once APP_ROOT . 'model/common/scrolling.php';
require_once APP_ROOT . 'model/common/categories.php';
require_once APP_ROOT . 'model/common/session.php';
require_once APP_ROOT . 'model/common/form.php';
require_once APP_ROOT . 'model/common/date.php';


// create/update form
class ScrollingFormController extends FormController {

	var $admin_user = false;
	var $staff_user = false;
	var $view; // current view

	function setUserType($admin_user=false, $staff_user = false) {
		$this->admin_user = $admin_user;
        $this->staff_user = $staff_user;
	}

    function setView(&$view) {
    	$this->view = $view;
    }


	 function ScrollingFormController() {
     	$this->addChild('create', new ButtonController(new Delegate($this, 'create'))); // create
        $this->addChild('save', new ButtonController(new Delegate($this, 'save'))); // save
        $this->addChild('delete', new ButtonController(new Delegate($this, 'delete'))); // delete

        $this->addChild('clean', new ButtonController(new Delegate($this, 'clean'))); // clean
        $this->addChild('list', new ButtonController(new Delegate($this, 'back'))); //

        $this->setDefaultChild('clean');

        // validation
		$this->addRule(new Handle('RequiredRule', array('headline')));
        $this->addRule(new Handle('SizeRangeRule', array('headline', 50)));


        $this->registerOnLoadListener(new Delegate($this, 'load'));
        //$this->registerOnActivateListener(new Delegate($this, 'check'));

        $this->addView('delete', new Handle('RedirectView', array('/delete')));

	 }

	 function makeExpireDate(&$responseModel) {
            //prepare expiration_date
            $day = $responseModel->get('expire_day');
            $month = $responseModel->get('expire_month');
            $year = $responseModel->get('expire_year');

            if ($day>0 && $month>0 && $year>2000) {
            	$expiration_date = gmmktime(0,0,0, $month,$day,$year);
            	//$tz =& new MyTimeZone();
            	//$expiration_date = $tz->timeLocal($expiration_date);
                $responseModel->set('expiration_date',gmdate("Y-m-d",$expiration_date));
            }
	 }

     function checkCategories(&$source, &$request, &$responseModel) {
        // check that two categories are linked
            $category_id = $responseModel->get('category_id');
            $category2_id = $responseModel->get('category2_id');

            //print $category_id.'/'.$category2_id ;
            // allow the categories to be unselected
            //if (!$category_id && !$category2_id) {
                //$responseModel->set('msg',"Error: At least one category must be selected!");
            	//return false;
            //}
            if ($category_id && $category2_id) {
            	$linked = CategoriesModel::AreCategoriesLinked($category_id, $category2_id);
            	//print 'result of check '.$linked;
            	if (!$linked) {
                    $responseModel->set('msg',"Error: The categories selected are not linked!");
                    //print $category_id.'/'.$category2_id." Not Linked!";
            		return false;
            	}
            }
            return true;
     }

     function create(&$source, &$request, &$responseModel) {
     	if ($responseModel->isValid()) {
            require_once WACT_ROOT.'/util/phpcompat/clone.php';

            if (!$this->checkCategories($source, $request, $responseModel) ) return 'this';


            //prepare expire_date
            $this->makeExpireDate($responseModel);

            //prepare author user
            $author_user_id = 0;
            if (Session::isLogin()) {
            	$author_user_id = Session::getUserId();
            }
            if ($author_user_id) $responseModel->set('user_id',$author_user_id);

            $tz =& new MyTimeZone();
            $now = $tz->timeNowLocal();

            $responseModel->set('date_posted', gmdate("Y-m-d H:i", $now) );
            $responseModel->set('enabled', 1);

            $id = Scrolling::insertItem($responseModel);
            if ($id) {
            	$responseModel->set('id', $id);
                $lastRecord = clone_obj($responseModel);


                // Set up the model for adding the next record
                $responseModel->removeAll();
                $responseModel->set('LastRecord', $lastRecord);


                return 'createOK';
            } else {
                return 'failure';
            }
        } else {
            //$responseModel->set('ShowPreview', TRUE);
        }
     }


	 function delete(&$source, &$request, &$responseModel) {
	 	return 'delete';
	 }


     function save(&$source, &$request, &$responseModel) {
        if ($responseModel->isValid()) {
        	$id = $request->getParameter('id');

        	if (!$this->checkCategories($source, $request, $responseModel) ) return 'this';

            //prepare show_date
            $this->makeExpireDate($responseModel);

            //prepare author user
            $admin_user_id = 0;
            if (Session::isLogin()) {
            	$admin_user_id = Session::getUserId();
            }
            if ($admin_user_id) $responseModel->set('user_id',$admin_user_id);
            $responseModel->set('enabled', 1);

            if ($id) Scrolling::updateItem($id, $responseModel);
            return 'saveOK';
        }
    }

    function clean(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'cleanOK';
    }

    function back(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'index';
    }

    // load show_date
    function loadExpirationDate(&$responseModel) {
       if ($responseModel->hasProperty('expiration_date')) {
       		$expiration_date = $responseModel->get('expiration_date');
       		//print $expiration_date.'<br>';
       		//print strtotime($date_show);
       		$ts = strtotime($expiration_date);
            $tz =& new MyTimeZone();
            $ts = $tz->timeGMT($ts);

       		$day = (integer)gmdate('d',$ts);
       		$month = (integer)gmdate('m',$ts);
       		$year = (integer)gmdate('Y',$ts);
       		$hour = (integer)gmdate('H',$ts);
            $minute = (integer)gmdate('i',$ts);
       		//print "   ".$day."/".$month."/".$year.'/'.$hour.":".$minute;
       		if ($day>0) $responseModel->set('expire_day',$day);
            if ($month>0) $responseModel->set('expire_month',$month);
            if ($year>0) $responseModel->set('expire_year',$year);
       }

    }

     function load(&$source, &$request, &$responseModel) {
     	$id = $request->getParameter('id');

     	if ($id) {
        	$record =& Scrolling::getRecord($id);
        	if (is_null($record)) {
            	return 'notfound';
        	}
            $responseModel->import($record->export());

            // load expiration date
            $this->loadExpirationDate($responseModel);

            //load width and height of the image
            $photo_url = $responseModel->get('photo_url');
            //$url = urlencode(HOST.$photo_url);
            $url = HOST.$photo_url;
	    $url = str_replace(' ','%20',$url); //REPLACE THE SPACES  
            list($width, $height, $type, $attr) = @getimagesize($url);
            $responseModel->set('photo_width', $width);
            $responseModel->set('photo_height', $height);
            //print  HOST.$photo_url;
            //print  $url.'.'.$width.'.'.$height;

            // prepare the author
            $author_show = User::getFullUserName($responseModel);
            $responseModel->set('author_show', $author_show);


        }
     }

     //prepare the form view
     function prepare(&$source, &$request, &$responseModel, &$template) {
     	//print 'Prepare form...';
     	if ($this->admin_user) {
     		$responseModel->set('admin_user',1);
     	}
     	if ($this->staff_user) $responseModel->set('staff_user',1);

     	//$template =& $view->Template;

        //populate months
        $expire_month =& $template->getChild('expire_month');
        $months_list =& SportDate::getMonthsList();
        $expire_month->setChoices($months_list);

        //print_r($responseModel);


        //prepopulate date
        $cur_month = (integer)date("m");
        $cur_year = (integer)date("Y");
        $cur_day = (integer)date("d");

        if ( $cur_month==1 ) {
        	$prev_month = 12;
        	$prev_year = $cur_year-1;
        }  else {
           $prev_month = $cur_month - 1;
           $prev_year = $cur_year;
        }

        if ( $cur_month==12 ) {
        	$next_month = 1;
        	$next_year = $cur_year+1;
        }  else {
           $next_month = $cur_month + 1;
           $next_year = $cur_year;
        }

        $expire_day =& $template->getChild('expire_day');
        $day = $expire_day->getValue();
        if (!$day) $expire_day->setValue($cur_day);

        if ($expire_month->getValue()<=0) $expire_month->setSelection($cur_month);


        $expire_year =& $template->getChild('expire_year');
        $year = $expire_year->getValue();
        if (!$year) $expire_year->setValue($cur_year);

        //populate categories
        $categories1 =& CategoriesModel::getSportCategories(false,false,true);
        $categories2 =& CategoriesModel::getCommunityCategories(false,false,true);
        $category1 =& $template->getChild('category_id');
        $category2 =& $template->getChild('category2_id');
        $category1->setChoices($categories1);
        $category2->setChoices($categories2);

        //populate orientation
        $orientations_list =& Scrolling::getOrientations();
        $orientation =& $template->getChild('orientation');
        $orientation->setChoices($orientations_list);



     }



}

?>